package com.jkhan.demo.ioflow;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @ClassName FileReaderTest
 * @Description FileReaderTest
 * @Author hjk
 * @Date 2022/2/15 19:22
 **/
public class FileReaderTest {
    public static void main(String[] args) {
        //提供File对象，指明读的对象
        File file = new File("hello.txt");

        //提供fileReader实例，用于数据读入
        FileReader fileReader = null;

        //读入操作
        try {
            fileReader = new FileReader(file);

            int len;//每次读入的长度
            char[] bytes = new char[5];
            while ((len = fileReader.read(bytes)) != -1) {
                //方式一
                for (int i = 0; i < len; i++) {
                    System.out.print(bytes[i]);
                }
                //方式二
                String str = new String(bytes, 0, len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //流关闭
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
